/**
 * 
 */
package br.com.lazyprogrammer.worldsoccermanager.fragments.main;

import br.com.lazyprogrammer.worldsoccermanager.MainActivity;
import br.com.lazyprogrammer.worldsoccermanager.R;
import br.com.lazyprogrammer.worldsoccermanager.network.model.User;
import br.com.lazyprogrammer.worldsoccermanager.network.model.dao.UserDAO;
import br.com.lazyprogrammer.worldsoccermanager.network.Request;
import br.com.lazyprogrammer.worldsoccermanager.network.interfaces.RegisterListener;
import br.com.lazyprogrammer.worldsoccermanager.network.task.IsEmailAvailableTask;
import br.com.lazyprogrammer.worldsoccermanager.network.task.IsUsernameAvailableTask;
import br.com.lazyprogrammer.worldsoccermanager.network.task.RegisterTask;
import br.com.lazyprogrammer.worldsoccermanager.preferences.interfaces.OnPreferencesChangedListener;
import br.com.lazyprogrammer.worldsoccermanager.system.generator.Generator;
import br.com.lazyprogrammer.worldsoccermanager.system.keyboard.Keyboard;
import br.com.lazyprogrammer.worldsoccermanager.system.mail.Email;
import br.com.lazyprogrammer.worldsoccermanager.system.message.Message;
import br.com.lazyprogrammer.worldsoccermanager.util.Constants;
import br.com.lazyprogrammer.worldsoccermanager.util.PoolData;

import android.app.Activity;
import android.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

/**
 * 
 * @author Limao Games <br />
 * <b>Email:</b> andreikeda@limaogames.com.br <br />
 * created on: 13/01/2014
 * @version 1.0
 * @see 
 */
public class RegisterFragment extends Fragment implements Request.Callback, OnClickListener, OnFocusChangeListener,
        RegisterListener {

	private UserDAO userDAO	= new UserDAO();
	
	private Button buttonRegister;
	private EditText inputDescription, inputEmail, inputPassword, inputUsername;
	private ImageView iconEmailAvailability, iconPasswordAvailability, iconUsernameAvailability;
	private LinearLayout layoutLoading;
	private ProgressBar loadingEmailAvailability, loadingUsernameAvailability;

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionCancel(java.lang.Class)
	 */
	@Override
	public void onCancel(Class<?> executingClass) {
		if (executingClass.equals(IsEmailAvailableTask.class))
			loadingEmailAvailability.setVisibility(View.GONE);
		if (executingClass.equals(IsUsernameAvailableTask.class))
			loadingUsernameAvailability.setVisibility(View.GONE);
		if (executingClass.equals(RegisterTask.class))
			layoutLoading.setVisibility(View.GONE);
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionError(java.lang.Class, java.lang.String)
	 */
	@Override
	public void onError(Class<?> executingClass, Request.Response result, String errorMessage) {
		Message.send(getActivity(), errorMessage);
		if (executingClass.equals(RegisterTask.class)) {
			layoutLoading.setVisibility(View.GONE);
		}
		if (executingClass.equals(IsEmailAvailableTask.class)) {
			loadingEmailAvailability.setVisibility(View.GONE);
			iconEmailAvailability.setImageResource(R.drawable.icon_unavailable);
		}
		if (executingClass.equals(IsUsernameAvailableTask.class)) {
			loadingUsernameAvailability.setVisibility(View.GONE);
			iconUsernameAvailability.setImageResource(R.drawable.icon_unavailable);
		}
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionStart(java.lang.Class)
	 */
	@Override
	public void onStart(Class<?> executingClass) {
		if (executingClass.equals(IsEmailAvailableTask.class))
			loadingEmailAvailability.setVisibility(View.VISIBLE);
		if (executingClass.equals(IsUsernameAvailableTask.class))
			loadingUsernameAvailability.setVisibility(View.VISIBLE);
		if (executingClass.equals(RegisterTask.class))
			layoutLoading.setVisibility(View.VISIBLE);
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.interfaces.ActionCallback#onActionSuccess(java.lang.Object, java.lang.Class)
	 */
	@Override
	public void onSuccess(Class<?> executingClass, Object result) {
		if (executingClass.equals(IsEmailAvailableTask.class)) {
			loadingEmailAvailability.setVisibility(View.GONE);
			iconEmailAvailability.setImageResource(R.drawable.icon_available);
		}
		if (executingClass.equals(IsUsernameAvailableTask.class)) {
			loadingUsernameAvailability.setVisibility(View.GONE);
			iconUsernameAvailability.setImageResource(R.drawable.icon_available);
		}
		if (executingClass.equals(RegisterTask.class))
			((MainActivity) getActivity()).goToConfirmAccountScreen();
	}
	
	@Override
	public void onClick(View v) {
		if (v.equals(buttonRegister))
			register();
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnFocusChangeListener#onFocusChange(android.view.View, boolean)
	 */
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		if (!hasFocus) {
			if (v.equals(inputEmail)) {
				if (Email.isValidEmail(getInputEmailText()))
					userDAO.isEmailAvailable(getActivity(), this, getInputEmailText());
				else
					iconEmailAvailability.setImageResource(R.drawable.icon_unavailable);
			}
			if (v.equals(inputUsername)) {
				if (isInputUsernameFilled())
					userDAO.isUsernameAvailable(getActivity(), this, getInputUsernameText());
				else
					iconUsernameAvailability.setImageResource(R.drawable.icon_unavailable);
			}
			if (v.equals(inputPassword)) {
				if (isInputPasswordFilled())
					iconPasswordAvailability.setImageResource(R.drawable.icon_available);
				else
					iconPasswordAvailability.setImageResource(R.drawable.icon_unavailable);
			}
		}
	}

	public void setViews(View view) {
		buttonRegister	= (Button) view.findViewById(R.id.button_register);
		
		inputDescription	= (EditText) view.findViewById(R.id.input_description);
		inputEmail			= (EditText) view.findViewById(R.id.input_email);
		inputPassword		= (EditText) view.findViewById(R.id.input_password);
		inputUsername		= (EditText) view.findViewById(R.id.input_username);
		
		iconEmailAvailability		= (ImageView) view.findViewById(R.id.icon_email_availability);
		iconPasswordAvailability	= (ImageView) view.findViewById(R.id.icon_password_availability);
		iconUsernameAvailability	= (ImageView) view.findViewById(R.id.icon_username_availability);
		
		layoutLoading	= (LinearLayout) view.findViewById(R.id.layout_loading);
		
		loadingEmailAvailability	= (ProgressBar) view.findViewById(R.id.loading_email);
		loadingUsernameAvailability	= (ProgressBar) view.findViewById(R.id.loading_username);

        inputPassword.setTypeface(null, Typeface.NORMAL);
        inputPassword.setTransformationMethod(new PasswordTransformationMethod());
	}

	public void setListeners() {
		buttonRegister.setOnClickListener(this);
		
		inputEmail.setOnFocusChangeListener(this);
		inputPassword.setOnFocusChangeListener(this);
		inputUsername.setOnFocusChangeListener(this);
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.app.communication.eai.abstracts.fragment.MainFragment#onFragmentCreatedView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_register, container, false);
		setViews(view);
		setListeners();
		return view;
	}

	/* (non-Javadoc)
	 * @see br.com.limaogames.games.sports.managersoccer.network.interfaces.RegisterListener#onRegisterSuccessful(br.com.limaogames.games.sports.managersoccer.model.User)
	 */
	@Override
	public void onRegisterSuccessful(User user, String password) {
		// TODO Auto-generated method stub
		PoolData.mPref.onPasswordChanged(password);
        PoolData.mPref.onUserIdChanged(user.getId());
        PoolData.mPref.onUsernameChanged(user.getUsername());

        PoolData.user = user;
	}
	
	private void register() {
		if (isInputPasswordFilled() && isInputEmailFilled() && isInputUsernameFilled()) {
			if (Email.isValidEmail(getInputEmailText())) {
				if (!userDAO.isRegisterTaskRunning()) {
					Keyboard.close(getActivity(), inputEmail);
					userDAO.register(
							getActivity(), 
							this, 
							this,
							Generator.encodeId(getInputUsernameText(), getInputEmailText(), getResources().getConfiguration().locale),
							getInputEmailText(), 
							getInputUsernameText(), 
							Generator.encodePassword(getInputPasswordText(), getResources().getConfiguration().locale), 
							getInputDescriptionText(), 
							Generator.createKey(Constants.DEFAULT_KEY_SIZE));
				}
			}
			else
				Message.send(getActivity(), R.string.exception_email_invalid);
		}
		else
			Message.send(getActivity(), R.string.exception_empty_field);
	}
	
	private String getInputDescriptionText() {
		return inputDescription.getText().toString();
	}
	
	private String getInputEmailText() {
		return inputEmail.getText().toString();
	}
	
	private String getInputPasswordText() {
		return inputPassword.getText().toString();
	}
	
	private String getInputUsernameText() {
		return inputUsername.getText().toString();
	}
	
	private boolean isInputEmailFilled() {
		return !getInputEmailText().equals("");
	}
	
	private boolean isInputPasswordFilled() {
		return !getInputPasswordText().equals("");
	}
	
	private boolean isInputUsernameFilled() {
		return !getInputUsernameText().equals("");
	}

}
